package cn.tedu.coolshark.filter;

import cn.tedu.coolshark.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤器
 */
@WebFilter(filterName = "loginFilter",urlPatterns = {"/product/insert1"})
public class LoginFilter implements Filter {
    /*过滤器初始化*/
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("过滤器执行了!");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取session对象
        HttpSession session = request.getSession();
        //从session中获取用户信息
        User user = (User)session.getAttribute("user");
        if (user == null) { //null则代表未登录
            //response.sendRedirect("/login.html");
            System.out.println("未登录!");
            return;
        }
        //如果用户登录了,则放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    /*过滤器销毁方法*/
    @Override
    public void destroy() {
    }
}
